// miniprogram/pages/skechToColor/skechToColor.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
const Multipart = require('../../Multipart.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    myOpenId: "",
    skechfileList: [], //上传的线稿
    learnfileList: [], //上传的参考图片
    // colorfileList: [], 
    genUrl: "", //生成的风格转换图片
    saveFileList: [], //以clound:形式写入数据库的图片
    saveGen: "", //base64编码,
    resultImage: ""
  },

  // 处理多张线稿图片待开发
  moreTips() {
    Toast.fail('开发中')
  },

  // 图片规格大小提醒
  sizeTips() {
    Toast('请上传对应512x512大小图片')
  },

  // 拿到线稿图片
  readSkech(event) {
    console.log(event)
    console.log('线稿', event.detail.file);
    this.data.skechfileList.push(event.detail.file);
    console.log(this.data.skechfileList)
    this.setData({
      skechfileList: this.data.skechfileList
    })
  },

  readLearn(event) {
    console.log('参考图片', event.detail.file);
    this.data.learnfileList.push(event.detail.file);
    this.setData({
      learnfileList: this.data.learnfileList
    })
  },

  // 删除上传的线稿图片
  deleteSkech(event) {
    console.log(event);
    this.data.skechfileList.splice(0, 1);
    console.log(this.data.skechfileList)
    this.setData({
      skechfileList: this.data.skechfileList
    })
  },

  deleteLearn(event) {
    console.log(event);
    this.data.learnfileList.splice(0, 1);
    console.log(this.data.learnfileList);
    this.setData({
      learnfileList: this.data.learnfileList
    })
  },

  // 发送生成图片请求
  requestGenerate() {
    if (this.data.skechfileList.length == 0 && this.data.learnfileList.length == 0) {
      Toast.fail("请上传线稿和参考图片")
    } else if (this.data.skechfileList.length == 0) {
      Toast.fail("请上传线稿")
    } else if (this.data.learnfileList.length == 0) {
      Toast.fail("请上传参考图片")
    } else {
      wx.showLoading({
        title: '生成中，勿操作',
        mask: true
      })
      var that = this;
      // 要不要等待拿好数据,同步发送请求
      console.log("线稿", this.data.skechfileList);
      console.log("参考图片", this.data.learnfileList);
      // 发送请求
      let multi = new Multipart({
        fields: [{
          name: 'token',
          value: 'gdsgfhdgjukfdk'
        }, {
          name: 'username',
          value: 'rainbowLover'
        }],
        files: [{
            filePath: that.data.skechfileList[0].url, //文件路径 
            filename: 'contour', //文件名称
            name: 'contour', //字段名
          },
          {
            filePath: that.data.learnfileList[0].url, //文件路径
            filename: 'ref', //文件名称 
            name: 'ref',
          }
        ]
      })
      multi.submit('https://fenshuaxiaojiang.vip.cpolar.cn/')
        .then(
          (res) => {
            console.log(res)
            /// 获取到base64Data
            var base64Data = res.data;
            /// 通过微信小程序自带方法将base64转为二进制去除特殊符号，再转回base64
            base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
            that.data.saveGen = base64Data;
            /// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
            const base64ImgUrl = "data:image/png;base64," + base64Data;
            /// 刷新数据
            console.log(base64ImgUrl);
            this.setData({
              genUrl: base64ImgUrl
            })
            console.log("进入存之前", that.data.genUrl);
            // 存进云存储和自己数据库里
            this.saveImages();
            console.log("隐藏之前完成存储");
            // this.onLoad();
          },
          (err) => {
            Toast.fail("请求失败");
          })
    }
  },

  // 预览生成图
  previewGen(e) {
    var generateIndex = e.currentTarget.dataset.index;
    var genfileList = [];
    genfileList.push(this.data.genUrl);
    wx.previewImage({
      urls: genfileList,
      current: genfileList[generateIndex]
    })
  },

  // 当生成成功后，把三张图片写进数据库自己有的地方,那就要先存进云存储
  saveImages() {
    // 分别拿到三张图片
    var that = this;
    console.log("进入存之后", that.data.genUrl);
    var tempFileList = [
      that.data.skechfileList[0].url,
      that.data.learnfileList[0].url,
      that.data.genUrl
    ];
    console.log(tempFileList)
    console.log(tempFileList.length)
    // 先存进云存储，临时路径在下一次打开小程序就失效了
    var cloudfileName = Date.now() + '/' + Math.floor(Math.random() * 10000 + 10000) + '.jpg';
    wx.cloud.uploadFile({
      cloudPath: cloudfileName,
      filePath: tempFileList[0],
      success: res => {
        console.log("上传完第1张")
        console.log(res);
        that.data.saveFileList.push(res.fileID);
        console.log(that.data.saveFileList);
        console.log(that.data.saveFileList.length);
        var cloudfileName = Date.now() + '/' + Math.floor(Math.random() * 10000 + 10000) + '.jpg';
        wx.cloud.uploadFile({
          cloudPath: cloudfileName,
          filePath: tempFileList[1],
          success: res => {
            console.log("上传完第2张")
            console.log(res);
            that.data.saveFileList.push(res.fileID);
            console.log(that.data.saveFileList);
            console.log(that.data.saveFileList.length);
            // 存生成图
            // 先将base64转为字节流，再转为url，最后存进云存储
            var arrayBuffer = wx.base64ToArrayBuffer(that.data.saveGen)
            console.log(arrayBuffer);
            const fsm = wx.getFileSystemManager();
            const FILE_BASE_NAME = 'qrcode_base64src';
            const filePath = wx.env.USER_DATA_PATH + '/' + FILE_BASE_NAME + '.jpg';
            fsm.writeFile({
              filePath,
              data: arrayBuffer,
              encoding: 'binary',
              success() {
                console.log("成功")
                that.setData({
                  resultImage: filePath //结果图片
                })
                console.log(that.data.resultImage);
                var cloudfileName1 = Date.now() + '/' + Math.floor(Math.random() * 10000 + 10000) + '.jpg';
                wx.cloud.uploadFile({
                  cloudPath: cloudfileName1,
                  filePath: that.data.resultImage,
                  success: res => {
                    console.log("上传完第3张")
                    console.log(res.fileID);
                    that.data.saveFileList.push(res.fileID);
                    console.log(that.data.saveFileList);
                    db.collection('userInfo').where({
                      _openid: that.data.myOpenId
                    }).update({
                      data: {
                        haveSkechs: _.push(that.data.saveFileList[0]),
                        haveLearnPics: _.push(that.data.saveFileList[1]),
                        haveColoizations: _.push(that.data.saveFileList[3])
                      },
                      success(res) {
                        console.log("成功将三张图存进对应数据库字段里")
                        // 存完要将that.data.saveFileList清空
                        that.data.saveFileList.splice(0, 3);
                        wx.hideLoading({
                          success: (sus) => {
                            console.log("放好进数据库才隐藏")
                            Toast.success("生成成功")
                          },
                        })
                      },
                      fail(err) {
                        // 失败也要清空
                        that.data.saveFileList.splice(0, 3);
                        wx.hideLoading({
                          success: (sus) => {
                            console.log("放好进数据库失败")
                            Toast.success("生成失败")
                          },
                        })
                      }
                    })
                  },
                  fail(uploadErr) {
                    wx.hideLoading({
                      success: (sus) => {
                        that.data.saveFileList.splice(0, 2);
                        console.log("生成图上传云存储失败")
                        Toast.success("生成失败")
                      },
                    })
                  }
                })
              },
              fail(writeErr) {
                wx.hideLoading({
                  success: (sus) => {
                    that.data.saveFileList.splice(0, 2);
                    console.log("生成图片改格式失败")
                    Toast.success("生成失败")
                  },
                })
              }
            })
          }
        })
      }
    })
    //   wx.cloud.callFunction({
    //     name: 'file',
    //     data: {
    //       path: Date.now() + '/' + Math.floor(Math.random() * 10000 + 10000) + '.jpg',
    //       file: that.data.saveGen
    //     },
    //     success(_res) {
    //       console.log(_res)
    //     },
    //     fail(_res) {
    //       console.log(_res)
    //     }
    //   })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(app.globalData);
    this.data.myOpenId = app.globalData.openid
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})